package com.siao.utils.string
{
	import com.siao.data.HashMap;
	
	/**
	 * 模板字符串
	 * @author SiaoLeon
	 */
	public class TempletString
	{
		// -------------------------------------------------------------------------------------------------------- 静态常量
		
		// -------------------------------------------------------------------------------------------------------- 静态变量
		
		private static var Map:HashMap = new HashMap();
		
		// -------------------------------------------------------------------------------------------------------- 静态方法
		
		/**
		 * 注册模板
		 * @param keyword
		 * @param value
		 */
		public static function register(keyword:String, value:Object):void
		{
			Map.put("{" + keyword + "}", value);
		}
		
		/**
		 * 解析替换文本内容
		 * @param content
		 * @return
		 */
		public static function parse(content:String):String
		{
			var regex:RegExp = new RegExp("(?P<keyword>\\{[^\\}]+\\})");
			
			while (regex.test(content))
			{
				var res:Object = regex.exec(content);
				var resIndex:int = res.index;
				var resKeyword:String = res.keyword;
				
				content = content.substr(0, resIndex) + Map.getValue(resKeyword) + content.substr(resIndex + resKeyword.length);
			}
			
			return content;
		}
		
		// -------------------------------------------------------------------------------------------------------- 静态函数
		
		// -------------------------------------------------------------------------------------------------------- 属性
		
		// -------------------------------------------------------------------------------------------------------- 变量
		
		private var content:String;
		
		// -------------------------------------------------------------------------------------------------------- 构造
		
		public function TempletString(content:String)
		{
			this.content = content;
		}
		
		// -------------------------------------------------------------------------------------------------------- 方法
		
		public function parse(keyword:String, value:Object):TempletString
		{
			while (this.content.indexOf("{" + keyword + "}") >= 0)
			{
				this.content = this.content.replace("{" + keyword + "}", value);
			}
			
			return this;
		}
		
		public function toString():String
		{
			return this.content;
		}
	
		// -------------------------------------------------------------------------------------------------------- 函数
	
	}
}
